<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="EduBot - 基于AI的图像处理平台，可检测趴桌、使用手机、站立、抬头等课堂异常行为">
    <meta name="keywords" content="EduBot,教育小助手,课堂异常行为检测,AI图像处理,行为识别,教育科技,课堂监控,学生行为分析,人工智能检测,教育管理,智能课堂,行为分析系统">
    <meta name="author" content="郑恩赐">
    <meta property="og:title" content="EduBot - 课堂异常行为检测系统">
    <meta property="og:description" content="基于AI的课堂异常行为检测系统，帮助教师及时发现和处理课堂异常行为">
    <meta property="og:type" content="website">
    <title>EduBot - 图像行为分析</title>
    <link rel="icon" type="image/png" href="static/icons/AiKeTangJiaoXuePingCeXiTong.png">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="{{ url_for('static', filename='javascripts/ImageProcessing.js') }}"></script>
    <style>
        :root {
            --primary-color: #4a80ff;
            --secondary-color: #6366f1;
            --accent-color: #00ffff;
            --dark-bg: #111827;
            --darker-bg: #1a1a2e;
            --text-color: #ffffff;
            --border-color: rgba(74, 128, 255, 0.2);
            --card-bg: rgba(74, 128, 255, 0.05);
            --hover-bg: rgba(74, 128, 255, 0.1);
            --glow-color: rgba(74, 128, 255, 0.5);
        }

        body {
            background-color: var(--dark-bg);
            color: var(--text-color);
            font-family: 'Orbitron', sans-serif;
            line-height: 1.6;
            background-image: 
                linear-gradient(45deg, rgba(74, 128, 255, 0.05) 1px, transparent 1px),
                linear-gradient(-45deg, rgba(74, 128, 255, 0.05) 1px, transparent 1px);
            background-size: 40px 40px;
        }

        .container {
            max-width: 1600px;
            margin: 0 auto;
            padding: 20px;
        }
        
        header {
            text-align: center;
            margin-bottom: 40px;
            padding: 40px;
            background: linear-gradient(135deg, var(--darker-bg) 0%, rgba(74, 128, 255, 0.1) 100%);
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(74, 128, 255, 0.2);
            border: 1px solid var(--border-color);
            position: relative;
            overflow: hidden;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: nowrap;
        }
        
        header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 2px;
            background: linear-gradient(90deg, transparent, var(--primary-color), transparent);
            animation: glow 2s linear infinite;
        }
        
        @keyframes glow {
            0% { opacity: 0; }
            50% { opacity: 1; }
            100% { opacity: 0; }
        }
        
        h1 {
            color: var(--primary-color);
            font-size: 2.5em;
            margin-bottom: 20px;
            font-weight: 500;
            text-shadow: 0 0 10px var(--glow-color);
            letter-spacing: 2px;
        }
        
        .image-upload-section {
            background: var(--card-bg);
            padding: 40px;
            border-radius: 16px;
            border: 1px solid var(--border-color);
            margin-bottom: 40px;
            box-shadow: 0 8px 32px rgba(74, 128, 255, 0.2);
            backdrop-filter: blur(10px);
            position: relative;
            overflow: hidden;
        }
        
        .upload-area {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            margin: 20px 0;
            padding: 60px;
            border: 2px dashed var(--border-color);
            border-radius: 16px;
            transition: all 0.3s ease;
            min-height: 300px;
            background: rgba(74, 128, 255, 0.02);
            position: relative;
        }
        
        .upload-area:hover {
            border-color: var(--primary-color);
            box-shadow: 0 0 20px var(--glow-color);
        }
        
        .upload-area.has-image {
            min-height: 0;
            padding: 20px;
            border: none;
            background: transparent;
        }
        
        .upload-area.has-image .upload-icon,
        .upload-area.has-image .upload-text {
            display: none;
        }
        
        .upload-area.has-image .upload-button {
            margin: 0;
        }
        
        .upload-icon {
            font-size: 64px;
            color: var(--primary-color);
            margin-bottom: 20px;
            opacity: 0.8;
        }
        
        .upload-text {
            color: var(--text-color);
            font-size: 1.2em;
            margin-bottom: 30px;
            text-align: center;
            opacity: 0.8;
        }
        
        .upload-button {
            background: transparent;
            color: var(--primary-color);
            padding: 15px 30px;
            border: 2px solid var(--primary-color);
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            font-size: 1.1em;
            transition: all 0.3s ease;
            margin-bottom: 10px;
            position: relative;
            overflow: hidden;
        }
        
        .upload-button:hover {
            background: var(--primary-color);
            color: var(--dark-bg);
            transform: translateY(-2px);
            box-shadow: 0 0 20px var(--glow-color);
        }
        
        .upload-button::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(74, 128, 255, 0.2), transparent);
            animation: shine 2s infinite;
        }
        
        @keyframes shine {
            0% { left: -100%; }
            100% { left: 100%; }
        }
        
        .file-name {
            color: var(--text-color);
            margin-top: 10px;
            font-size: 14px;
            opacity: 0.8;
        }
        
        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .primary-btn {
            background: var(--primary-color);
            color: var(--dark-bg);
            border: none;
        }
        
        .primary-btn:hover {
            background: var(--primary-color);
            opacity: 0.9;
        }
        
        .secondary-btn {
            background: transparent;
            color: var(--secondary-color);
            border: 2px solid var(--secondary-color);
        }
        
        .secondary-btn:hover {
            background: var(--secondary-color);
            color: var(--dark-bg);
        }
        
        .image-preview-container {
            margin: 40px 0;
            text-align: center;
            padding: 30px;
            border: 1px solid var(--border-color);
            border-radius: 16px;
            background: var(--card-bg);
            box-shadow: 0 8px 32px rgba(74, 128, 255, 0.2);
            backdrop-filter: blur(10px);
        }
        
        .image-preview {
            margin: 30px 0;
        }
        
        .image-preview img {
            max-width: 100%;
            max-height: 600px;
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(74, 128, 255, 0.3);
            transition: all 0.3s ease;
        }
        
        .image-preview img:hover {
            transform: scale(1.02);
            box-shadow: 0 12px 40px rgba(74, 128, 255, 0.4);
        }
        
        .behavior-form {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: var(--card-bg);
            padding: 30px;
            border-radius: 16px;
            border: 1px solid var(--border-color);
            box-shadow: 0 8px 32px rgba(74, 128, 255, 0.3);
            backdrop-filter: blur(10px);
            z-index: 1000;
            min-width: 400px;
            max-width: 90%;
            display: none;
        }
        
        .behavior-form.show {
            display: block;
        }
        
        .behavior-form-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            z-index: 999;
            display: none;
        }
        
        .behavior-form-overlay.show {
            display: block;
        }
        
        .behavior-options {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin: 20px 0;
        }
        
        .behavior-option {
            display: flex;
            align-items: center;
            padding: 15px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            background: rgba(74, 128, 255, 0.02);
            transition: all 0.3s ease;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        
        .behavior-option:hover {
            background: var(--hover-bg);
            transform: translateY(-2px);
            box-shadow: 0 0 20px var(--glow-color);
            border-color: var(--primary-color);
        }
        
        .behavior-option input[type="checkbox"] {
            margin-right: 15px;
            width: 20px;
            height: 20px;
            accent-color: var(--primary-color);
            position: relative;
        }
        
        .behavior-option label {
            font-size: 1.1em;
            color: var(--text-color);
            cursor: pointer;
        }
        
        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 15px;
            margin-top: 30px;
        }
        
        .results-section {
            margin-top: 40px;
            padding: 40px;
            border: 1px solid var(--border-color);
            border-radius: 16px;
            background: var(--card-bg);
            box-shadow: 0 8px 32px rgba(74, 128, 255, 0.2);
            backdrop-filter: blur(10px);
        }
        
        .result-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 40px;
            margin: 40px 0;
        }
        
        .original-image, .processed-image {
            text-align: center;
            padding: 30px;
            border: 1px solid var(--border-color);
            border-radius: 16px;
            background: rgba(74, 128, 255, 0.02);
            transition: all 0.3s ease;
        }
        
        .original-image:hover, .processed-image:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 32px rgba(74, 128, 255, 0.3);
        }
        
        .original-image img, .processed-image img {
            max-width: 100%;
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(74, 128, 255, 0.3);
            transition: all 0.3s ease;
        }
        
        .original-image img:hover, .processed-image img:hover {
            transform: scale(1.02);
        }
        
        .detection-results {
            background: var(--card-bg);
            padding: 40px;
            border-radius: 16px;
            border: 1px solid var(--border-color);
            margin: 40px 0;
            box-shadow: 0 8px 32px rgba(74, 128, 255, 0.2);
            backdrop-filter: blur(10px);
        }
        
        .detection-results h3 {
            color: var(--primary-color);
            margin-bottom: 30px;
            font-size: 1.8em;
            font-weight: 300;
        }
        
        .detection-results p {
            color: var(--text-color);
            margin: 15px 0;
            font-size: 1.2em;
            opacity: 0.9;
        }
        
        .detection-results ul {
            list-style: none;
            padding: 0;
            margin: 30px 0;
        }
        
        .detection-results li {
            color: var(--text-color);
            margin: 15px 0;
            padding: 20px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            transition: all 0.3s ease;
            background: rgba(74, 128, 255, 0.02);
        }
        
        .detection-results li:hover {
            background: var(--hover-bg);
            transform: translateX(10px);
            box-shadow: 0 4px 16px rgba(74, 128, 255, 0.2);
        }
        
        .action-buttons {
            display: flex;
            justify-content: center;
            gap: 30px;
            margin-top: 40px;
        }
        
        .action-buttons .btn {
            min-width: 180px;
            padding: 15px 30px;
            font-size: 1.1em;
            border-radius: 8px;
            transition: all 0.3s ease;
        }
        
        .action-buttons .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(74, 128, 255, 0.3);
        }

        .modal {
            background-color: rgba(0, 0, 0, 0.7);
        }
        
        .modal-content {
            background: var(--darker-bg);
            border: 1px solid var(--border-color);
        }
        
        .modal-title {
            color: var(--primary-color);
        }
        
        .close-modal {
            color: var(--text-color);
        }
        
        .form-group label {
            color: var(--text-color);
        }
        
        .form-group input[type="text"],
        .form-group input[type="file"] {
            background: var(--dark-bg);
            border: 1px solid var(--border-color);
            color: var(--text-color);
            padding: 10px;
            border-radius: 4px;
        }

        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.9);
            backdrop-filter: blur(5px);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .status-message {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            padding: 15px 30px;
            background: rgba(17, 24, 39, 0.9);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            color: var(--text-color);
            font-size: 1.1em;
            box-shadow: 0 8px 32px rgba(74, 128, 255, 0.5);
            z-index: 1001;
            backdrop-filter: blur(10px);
            display: flex;
            align-items: center;
            justify-content: center;
            min-width: 250px;
            max-width: 90%;
            text-align: center;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s ease, transform 0.3s ease;
        }

        .status-message.visible {
            opacity: 1;
            transform: translateX(-50%) translateY(0);
            pointer-events: auto;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateX(-50%) translateY(-20px); }
            to { opacity: 1; transform: translateX(-50%) translateY(0); }
        }

        .status-message.success {
            border-left: 4px solid #4CAF50;
        }

        .status-message.error {
            border-left: 4px solid #F44336;
        }

        .status-message.loading {
            border-left: 4px solid var(--primary-color);
        }

        .status-message .loader {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid var(--primary-color);
            border-radius: 50%;
            border-top-color: transparent;
            margin-right: 10px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .modal-overlay.show {
            display: flex;
        }

        .modal-image {
            max-width: 95vw;
            max-height: 95vh;
            border-radius: 12px;
            box-shadow: 0 0 30px var(--glow-color);
            cursor: pointer;
            transition: transform 0.3s ease;
            border: 1px solid var(--border-color);
        }

        .modal-image:hover {
            transform: scale(1.02);
        }

        .behavior-images-container {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 40px;
            margin: 40px 0;
            max-width: 100%;
        }

        .behavior-image img {
            max-width: 100%;
            max-height: 500px;
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(74, 128, 255, 0.3);
            transition: all 0.3s ease;
        }

        @media (max-width: 1200px) {
            .container {
                max-width: 1200px;
            }
        }

        @media (max-width: 992px) {
            .container {
                max-width: 992px;
            }
        }

        @media (max-width: 768px) {
            .container {
                max-width: 768px;
                padding: 10px;
            }

            .image-preview img {
                max-height: 400px;
            }

            .behavior-image img {
                max-height: 400px;
            }

            header {
                padding: 20px;
                margin-bottom: 20px;
            }

            h1 {
                font-size: 1.5em;
                margin: 0 10px;
                white-space: nowrap;
            }

            .image-upload-section {
                padding: 20px;
            }

            .upload-area {
                padding: 30px;
                min-height: 200px;
            }

            .upload-button {
                padding: 12px 24px;
                font-size: 1em;
            }

            .behavior-images-container {
                grid-template-columns: 1fr;
                gap: 20px;
            }

            .behavior-image-container {
                margin: 20px 0;
            }

            .modal-image {
                max-width: 95vw;
                max-height: 95vh;
            }

            .action-buttons {
                flex-direction: column;
                gap: 15px;
            }

            .action-buttons .btn {
                width: 100%;
                margin: 5px 0;
            }

            .behavior-form {
                min-width: 90%;
                padding: 20px;
            }

            .behavior-options {
                grid-template-columns: 1fr;
            }

            .detection-results {
                padding: 20px;
            }

            .result-container {
                grid-template-columns: 1fr;
                gap: 20px;
            }

            .original-image, .processed-image {
                padding: 15px;
            }

            .detection-results h3 {
                font-size: 1.5em;
            }

            .detection-results p {
                font-size: 1em;
            }

            .detection-results li {
                padding: 15px;
                margin: 10px 0;
            }

            .nav-button {
                padding: 6px 12px;
                font-size: 0.8em;
                min-height: 32px;
                flex-shrink: 0;
            }

            header > div {
                width: 60px;
                flex-shrink: 0;
            }
        }

        @media (max-width: 480px) {
            .container {
                max-width: 480px;
            }

            .image-preview img {
                max-height: 300px;
            }

            .behavior-image img {
                max-height: 300px;
            }

            .upload-area {
                padding: 20px;
            }

            .upload-icon {
                font-size: 48px;
            }

            .upload-text {
                font-size: 1em;
            }

            .behavior-form {
                padding: 15px;
            }

            .behavior-option {
                padding: 10px;
            }

            .form-actions {
                flex-direction: column;
                gap: 10px;
            }

            .form-actions .btn {
                width: 100%;
            }
        }

        .nav-button {
            background: transparent;
            color: var(--primary-color);
            padding: 8px 15px;
            border: 2px solid var(--primary-color);
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            font-size: 0.9em;
            transition: all 0.3s ease;
            text-decoration: none;
            position: relative;
            overflow: hidden;
            white-space: nowrap;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 36px;
        }
        
        .nav-button:hover {
            background: var(--primary-color);
            color: var(--dark-bg);
            transform: translateY(-2px);
            box-shadow: 0 0 20px var(--glow-color);
        }
        
        .nav-button::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(74, 128, 255, 0.2), transparent);
            animation: shine 2s infinite;
        }
    </style>
</head>
<body>
    <h1 style="display: none;">EduBot - 图像行为分析</h1>
    <div class="container">
        <div class="status-message"></div>
        <header>
            <a href="{{ front_end_domain_name }}/navigation_page" class="nav-button">返回</a>
            <h1>模型效果体验</h1>
            <div style="width: 120px;"></div>
        </header>
        
        <main>
            <section class="image-upload-section">
                <div class="system-message">
                    <p>请选择一张图像</p>
                </div>
                <div class="upload-area">
                    <div class="upload-icon">📁</div>
                    <div class="upload-text">点击下方按钮选择文件</div>
                    <button id="showBehaviorFormBtn" class="btn primary-btn">选择图像文件</button>
                </div>
                <div class="image-preview-container" style="display: none;">
                    <h3>图像预览</h3>
                    <div class="image-preview">
                        <img id="previewImage" src="" alt="图像预览">
                    </div>
                </div>
                
                <div class="behavior-form-overlay"></div>
                <div class="behavior-form">
                    <h3>选择检测行为</h3>
                    <div class="behavior-options">
                        <div class="behavior-option">
                            <input type="checkbox" id="headOnDesk" name="behaviors" value="head_on_desk" checked>
                            <label for="headOnDesk">趴桌行为</label>
                        </div>
                        <div class="behavior-option">
                            <input type="checkbox" id="usePhone" name="behaviors" value="use_phone" checked>
                            <label for="usePhone">使用手机</label>
                        </div>
                        <div class="behavior-option">
                            <input type="checkbox" id="stand" name="behaviors" value="stand" checked>
                            <label for="stand">站立行为</label>
                        </div>
                        <div class="behavior-option">
                            <input type="checkbox" id="lookUp" name="behaviors" value="look_up" checked>
                            <label for="lookUp">抬头行为</label>
                        </div>
                    </div>
                    <div class="form-actions">
                        <button type="button" class="btn secondary-btn" id="cancelBehavior">取消</button>
                        <button type="button" class="btn primary-btn" id="confirmBehavior">确认</button>
                    </div>
                </div>
                <div class="process-controls" style="margin-top: 20px; text-align: center;">
                </div>
            </section>
            
            <section class="results-section" style="display: none;">
            </section>
        </main>
        
        <footer>
        </footer>
    </div>

    <!-- 添加模态框 -->
    <div id="uploadModal" class="modal">
    </div>

    <div class="modal-overlay">
        <img class="modal-image" src="" alt="放大图像">
    </div>

    <script>
        const frontEndDomain = "{{ front_end_domain_name }}";
        const backendDomain = "{{ backend_domain_name }}";
        
        let currentFormData = null;
        
        // 显示状态消息的函数
        function showStatusMessage(message, type = 'loading') {
            const statusMessage = $('.status-message');
            
            // 清除之前的内容
            statusMessage.empty();
            
            // 为加载状态添加加载图标
            if (type === 'loading') {
                statusMessage.append('<div class="loader"></div>');
            }
            
            // 添加消息文本
            statusMessage.append('<span>' + message + '</span>');
            
            // 设置样式类
            statusMessage.removeClass('success error loading').addClass(type);
            
            // 显示消息
            statusMessage.addClass('visible');
            
            // 非加载状态的消息自动消失
            if (type !== 'loading') {
                setTimeout(() => {
                    hideStatusMessage();
                }, 3000);
            }
        }

        // 隐藏状态消息的函数
        function hideStatusMessage() {
            $('.status-message').removeClass('visible');
        }
        
        $(document).ready(function() {
            // 检查token有效性
            checkToken(backendDomain, localStorage.getItem('token'))
                .then(isValid => {
                    if (!isValid) {
                        window.location.href = frontEndDomain + '/login_register_page';
                        return;
                    }
                })
                .catch(error => {
                    console.error('Token检查失败:', error);
                    window.location.href = frontEndDomain + '/login_register_page';
                });

            // 获取模态框元素
            const modal = $("#uploadModal");
            const behaviorForm = $(".behavior-form");
            const behaviorOverlay = $(".behavior-form-overlay");
            
            // 修改文件上传处理函数
            $("#showBehaviorFormBtn").click(function() {
                // 清除之前的结果
                $(".results-section").hide();
                $(".results-section").empty();
                $(".image-preview-container").hide();
                $(".upload-area").removeClass("has-image");
                
                // 创建文件输入元素
                const fileInput = document.createElement('input');
                fileInput.type = 'file';
                fileInput.accept = 'image/*';
                fileInput.style.display = 'none';
                
                // 添加文件选择事件处理
                fileInput.onchange = function(e) {
                    const file = e.target.files[0];
                    if (file) {
                        showStatusMessage('正在上传图片...', 'loading');
                        
                        // 压缩图片
                        compressImage(file, function(compressedBlob) {
                            showStatusMessage('正在处理图片...', 'loading');
                            
                            // 创建新的FormData对象
                            currentFormData = new FormData();
                            
                            // 确保使用正确的字段名 'image'，并添加原始文件名
                            const imageFile = new File([compressedBlob], file.name, {
                                type: 'image/jpeg',
                                lastModified: Date.now()
                            });
                            
                            currentFormData.append('image', imageFile);
                            
                            // 显示预览
                            const reader = new FileReader();
                            reader.onload = function(e) {
                                $("#previewImage").attr('src', e.target.result);
                                $(".image-preview-container").show();
                                $(".upload-area").addClass("has-image");
                                
                                // 自动获取所有选中的行为
                                const selectedBehaviors = [];
                                $("input[name='behaviors']:checked").each(function() {
                                    selectedBehaviors.push($(this).val());
                                });
                                
                                // 直接调用API处理图像
                                processImageApi(backendDomain, localStorage.getItem('token'), selectedBehaviors, imageFile)
                                    .then(response => {
                                        if (response.TF) {
                                            showStatusMessage('处理完成！', 'success');
                                            // 显示处理结果
                                            displayResults(response.data);
                                        } else {
                                            showStatusMessage(response.message || '处理失败', 'error');
                                        }
                                    })
                                    .catch(error => {
                                        console.error('处理图像时发生错误:', error);
                                        showStatusMessage('处理图像时发生错误，请尝试使用较小的图片或联系管理员', 'error');
                                    })
                                    .finally(() => {
                                        $(".loader").remove();
                                        hideStatusMessage();
                                    });
                            };
                            reader.readAsDataURL(compressedBlob);
                        });
                    }
                };
                
                // 触发文件选择
                fileInput.click();
            });
            
            // 图片压缩函数
            function compressImage(file, callback) {
                console.log('开始压缩图像:', file.name, '大小:', file.size, 'bytes');
                
                // 如果文件小于1MB，直接使用原文件
                if (file.size < 1024 * 1024) {
                    console.log('图像小于1MB，跳过压缩');
                    callback(file);
                    return;
                }
                
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function(e) {
                    const img = new Image();
                    img.src = e.target.result;
                    img.onload = function() {
                        const canvas = document.createElement('canvas');
                        let width = img.width;
                        let height = img.height;
                        
                        console.log('原始图像尺寸:', width, 'x', height);
                        
                        // 如果图片太大，进行缩放
                        const maxDimension = 1024; // 最大尺寸
                        if (width > maxDimension || height > maxDimension) {
                            if (width > height) {
                                height = Math.round((height * maxDimension) / width);
                                width = maxDimension;
                            } else {
                                width = Math.round((width * maxDimension) / height);
                                height = maxDimension;
                            }
                            console.log('调整后的图像尺寸:', width, 'x', height);
                        }
                        
                        canvas.width = width;
                        canvas.height = height;
                        const ctx = canvas.getContext('2d');
                        ctx.drawImage(img, 0, 0, width, height);
                        
                        // 转换为Blob对象
                        canvas.toBlob(function(blob) {
                            console.log('压缩后图像大小:', blob.size, 'bytes');
                            callback(blob);
                        }, 'image/jpeg', 0.85); // 稍微提高质量以保证图像清晰度
                    };
                };
            }
            
            // 处理图像按钮点击事件
            $("#processImageBtn").click(function() {
                // 显示行为选择表单
                behaviorForm.addClass("show");
                behaviorOverlay.addClass("show");
            });
            
            // 取消行为选择
            $("#cancelBehavior").click(function() {
                behaviorForm.removeClass("show");
                behaviorOverlay.removeClass("show");
            });
            
            // 点击遮罩层关闭表单
            behaviorOverlay.click(function() {
                behaviorForm.removeClass("show");
                behaviorOverlay.removeClass("show");
            });
            
            // 修改确认行为选择函数
            $("#confirmBehavior").click(function() {
                const selectedBehaviors = [];
                $("input[name='behaviors']:checked").each(function() {
                    selectedBehaviors.push($(this).val());
                });
                
                if (selectedBehaviors.length === 0) {
                    alert("请至少选择一个检测行为");
                    return;
                }
                
                if (!currentFormData) {
                    alert("请先选择图像文件");
                    return;
                }
                
                // 显示加载提示
                $("#processImageBtn").prop("disabled", true).text("处理中...");
                
                // 获取图像文件
                const imageFile = currentFormData.get('image');
                if (!imageFile) {
                    console.error('无法从currentFormData获取图像文件');
                    alert('图像处理失败：无法获取图像文件');
                    $("#processImageBtn").prop("disabled", false).text("处理图像");
                    $(".loader").remove();
                    return;
                }
                
                console.log('准备调用API，行为列表:', selectedBehaviors);
                console.log('图像文件:', imageFile.name, '大小:', imageFile.size);
                
                // 直接传递文件对象给API
                processImageApi(backendDomain, localStorage.getItem('token'), selectedBehaviors, imageFile)
                    .then(response => {
                        console.log('API返回结果:', response);
                        if (response.TF) {
                            // 显示处理结果
                            displayResults(response.data);
                            behaviorForm.removeClass("show");
                            behaviorOverlay.removeClass("show");
                        } else {
                            alert(response.message || '处理失败');
                        }
                    })
                    .catch(error => {
                        console.error('处理图像时发生错误:', error);
                        alert('处理图像时发生错误，请尝试使用较小的图片或联系管理员');
                    })
                    .finally(() => {
                        $(".loader").remove();
                        $("#processImageBtn").prop("disabled", false).text("处理图像");
                    });
            });
            
            // 显示处理结果的函数
            function displayResults(response) {
                console.log('显示处理结果:', response);
                
                // 显示处理结果区域
                $(".results-section").show();
                
                // 添加总人数显示
                const totalPeople = response.yolo_model_output ? response.yolo_model_output.length : 0;
                $(".results-section").prepend(`
                    <div class="total-people" style="text-align: center; margin-bottom: 20px;">
                        <h3 style="color: var(--primary-color);">检测到总人数：${totalPeople}</h3>
                    </div>
                `);
                
                // 设置原始图像
                $("#originalImage").attr('src', $("#previewImage").attr('src'));
                
                // 创建Canvas元素用于绘制检测框
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                const img = new Image();
                
                img.onload = function() {
                    // 设置Canvas尺寸与图像相同
                    canvas.width = img.width;
                    canvas.height = img.height;
                    
                    // 绘制原始图像
                    ctx.drawImage(img, 0, 0);
                    
                    // 绘制检测框
                    if (response.yolo_model_output) {
                        ctx.strokeStyle = '#FF4081';
                        ctx.lineWidth = 3;
                        
                        response.yolo_model_output.forEach((box) => {
                            const [x1, y1, x2, y2] = box;
                            ctx.strokeRect(x1, y1, x2 - x1, y2 - y1);
                        });
                    }
                    
                    // 将Canvas转换为图像URL并显示
                    const detectionImage = document.createElement('img');
                    detectionImage.src = canvas.toDataURL();
                    detectionImage.style.maxWidth = '100%';
                    detectionImage.style.borderRadius = '12px';
                    detectionImage.style.boxShadow = '0 8px 32px rgba(74, 128, 255, 0.3)';
                    
                    // 添加检测结果图像区域
                    $(".results-section").append(`
                        <div class="detection-image-container" style="text-align: center; margin: 40px 0;">
                            <h3 style="color: var(--primary-color); margin-bottom: 20px;">检测到的人</h3>
                            <div class="detection-image" style="display: inline-block;">
                                ${detectionImage.outerHTML}
                            </div>
                        </div>
                    `);

                    // 绘制行为检测结果
                    const behaviors = {
                        head_on_desk: { color: '#2196F3', label: '趴桌行为' },
                        use_phone: { color: '#9C27B0', label: '使用手机' },
                        stand: { color: '#FF9800', label: '站立行为' },
                        look_up: { color: '#4CAF50', label: '抬头行为' }
                    };

                    // 创建行为图像容器
                    const behaviorImagesContainer = $('<div class="behavior-images-container" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 40px; margin: 40px 0;"></div>');
                    $(".results-section").append(behaviorImagesContainer);

                    Object.entries(behaviors).forEach(([behavior, { color, label }]) => {
                        if (response[behavior]) {
                            const count = response[behavior].length;
                            
                            const behaviorCanvas = document.createElement('canvas');
                            const behaviorCtx = behaviorCanvas.getContext('2d');
                            behaviorCanvas.width = img.width;
                            behaviorCanvas.height = img.height;
                            
                            behaviorCtx.drawImage(img, 0, 0);
                            behaviorCtx.strokeStyle = color;
                            behaviorCtx.lineWidth = 3;
                            
                            response[behavior].forEach((box) => {
                                const [x1, y1, x2, y2] = box;
                                behaviorCtx.strokeRect(x1, y1, x2 - x1, y2 - y1);
                            });
                            
                            const behaviorImage = document.createElement('img');
                            behaviorImage.src = behaviorCanvas.toDataURL();
                            behaviorImage.style.maxWidth = '100%';
                            behaviorImage.style.borderRadius = '12px';
                            behaviorImage.style.boxShadow = '0 8px 32px rgba(74, 128, 255, 0.3)';
                            
                            behaviorImagesContainer.append(`
                                <div class="behavior-image-container" style="text-align: center;">
                                    <h3 style="color: ${color}; margin-bottom: 20px;">${label} - 检测到 ${count} 人</h3>
                                    <div class="behavior-image" style="display: inline-block;">
                                        ${behaviorImage.outerHTML}
                                    </div>
                                </div>
                            `);
                        }
                    });
                };
                
                img.src = $("#previewImage").attr('src');
                
                // 滚动到结果区域
                $(".results-section")[0].scrollIntoView({ behavior: "smooth" });
            }
            
            // 处理新图像按钮点击事件
            $("#newProcessBtn").click(function() {
                // 隐藏结果区域
                $(".results-section").hide();
                // 显示上传区域
                $(".image-upload-section").show();
                // 隐藏预览区域
                $(".image-preview-container").hide();
                // 移除has-image类
                $(".upload-area").removeClass("has-image");
                // 重置行为选择
                $("input[name='behaviors']").prop('checked', true);
                // 隐藏行为选择表单
                behaviorForm.removeClass("show");
                behaviorOverlay.removeClass("show");
            });

            // 在displayResults函数前增加关闭表单逻辑
            function handleFormClose() {
                behaviorForm.removeClass("show");
                behaviorOverlay.removeClass("show");
            }

            // 修改行为表单关闭逻辑
            behaviorOverlay.click(handleFormClose);
            $(document).on('keyup', function(e) {
                if (e.key === 'Escape') handleFormClose();
            });

            // 修改检测结果展示逻辑
            function createBehaviorItem(color, label, count) {
                return `<li style="border-left: 4px solid ${color}">
                    <span style="color: ${color}">${label}</span>：检测到 ${count} 次
                </li>`;
            }

            // 在图片处理时增加加载状态
            $("#processImageBtn").click(function() {
                $(".upload-area").append(`
                    <div class="loader" style="margin-top:20px;display:inline-block;
                        width:30px;height:30px;border:3px solid var(--primary-color);
                        border-radius:50%;border-top-color:transparent;
                        animation:spin 1s linear infinite">
                    </div>
                `);
            });

            // 添加图像点击放大功能
            $(".results-section").on('click', 'img', function() {
                const modalOverlay = $(".modal-overlay");
                const modalImage = $(".modal-image");
                modalImage.attr('src', $(this).attr('src'));
                modalOverlay.addClass('show');
            });

            // 点击模态框关闭
            $(".modal-overlay").click(function() {
                $(this).removeClass('show');
            });

            // 按ESC键关闭模态框
            $(document).keyup(function(e) {
                if (e.key === "Escape") {
                    $(".modal-overlay").removeClass('show');
                }
            });
        });
    </script>
</body>
</html>
